//
//  iMB_DownloadNetVideo.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-8-1.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "iMB_DownloadNetVideo.h"
#import <ASIHTTPRequest.h>

@implementation iMB_DownloadNetVideo

- (id)init {
    if (self = [super init]) {
        //--------------------- 观 察 progress --------------------
        [self addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"progress" context:NULL];
}

- (void)toDownloadNetVideoUrl:(NSString *)url downProgress:(DownloadProgress)downloadProgress {
    
    //--------------------- 网 络 视 频 地 址 --------------------
    NSString *urlstring = url;
    
    //--------------------- 本 地 存 储 视 频 地 址 --------------------
    // 创建文件夹
    NSString *fileName = FORMAT_STR(NET_VIDEO_DOWNLOAD_FINISHED_NAME);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:Baby_DownLoad_Video]) {
        [fileManager createDirectoryAtPath:Baby_DownLoad_Video withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *path = [Baby_DownLoad_Video stringByAppendingPathComponent:fileName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    
    //--------------------- ASI 下 载 --------------------
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlstring]];
    [request setHeadersReceivedBlock:^(NSDictionary *responseHeaders){
        // 响应头(需求放开使用即可)
        // NSDictionary *responseHeaders = request.responseHeaders;
        // NSLog(@"%@",responseHeaders);
        // 获取下载文件大小
        // NSNumber *contentSize = [responseHeaders objectForKey:@"Content-Length"];
        // NSLog(@"%@",contentSize);
    }];
    // 设置文件下载存放的路径
    [request setDownloadDestinationPath:path];
    // 设置进度条
    request.downloadProgressDelegate = self;
    
    //------------------------ 断 点 续 传 -----------------
    // 设置是否支持断点续传
    [request setAllowResumeForFileDownloads:YES];
    // 设置下载过程中暂存的文件路径
    NSString *tempPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/cache.download"];
    [request setTemporaryFileDownloadPath:tempPath];
    [request startAsynchronous];
    
    // block返回进度百分比
    _downloadProgress = downloadProgress;
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change context:(void *)context {
    NSNumber *value = [change objectForKey:@"new"];
    float progress = [value floatValue];
    _downloadProgress(progress);
}

@end
